import store from '@/store'

/**
 * 获取字典列表
 * @param {*} options 全局仓库存放字典的字段
 * @param {*} getDictFunc 获取字典值的api方法
 * @param {*} params api方法的参数列表
 */
export async function getDictItem (options, getDictFunc, params) {
  let result = null
  if (store.state.dictData[options]) {
    result = store.state.dictData[options]
  } else {
    const res = await getDictFunc(...params)
    if (res.code === 200) {
      store.commit('dictData/SET_DICT_VALUE', {
        key: options,
        options: res.rows
      })
      result = res.rows
    }
  }
  return result
}

/*金额处理*/
// 金额添加千分位
export const comdify = function (val) {
  if (!val) return val;
  let value='';
  if (val != null && val != '' && val!=undefined) {
    let n =val+"";
  let str = n.split('.');
  let re = /\d{1,3}(?=(\d{3})+$)/g;
  let n1 = str[0].replace(re, "$&,");
  value = str.length > 1 && str[1] ? `${n1}.${str[1]}` : `${n1}.00`;
  }
  return value;
};
//去除千分位中的‘，'
export const delcommafy = function (num){
  if(!num) return num;
  num = num.toString();
  num = num.replace(/,/gi, '');
  return num;
};
// 获取输入框的值
export const getInputValue = function (el) {
  let inputVal = el.target.value || '';
  let value =comdify(delcommafy(inputVal));
  return value;
};

// 对象深拷贝
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * 表格行合并数据处理
 * @param {*} data 源数据
 * @param {*} merge 合并字段
 */
export function mergeTableRow(data, merge) {
  if (!merge || merge.length === 0) {
    return data
  }
  merge.forEach((m) => {
    const mList = {}
    data = data.map((v, index) => {
      const rowVal = v[m]
      if (mList[rowVal] && mList[rowVal].newIndex === index) {
        mList[rowVal]['num']++
        mList[rowVal]['newIndex']++
        data[mList[rowVal]['index']][m + '-span'].rowspan++
        v[m + '-span'] = {
          rowspan: 0,
          colspan: 0
        }
      } else {
        mList[rowVal] = { num: 1, index: index, newIndex: index + 1 }
        v[m + '-span'] = {
          rowspan: 1,
          colspan: 1
        }
      }
      if (v.children && v.children.length > 0) {
        v.children.map((c) => {
          c[m + '-span'] = {
            rowspan: 0,
            colspan: 0
          }
        })
      }
      return v
    })
  })
  return data
}

/**
 * 树形数组扁平化
 * @param {Array} arr treeData
 */
export function flatteningArray (arr) {
  let res = []
  arr.forEach(el => {
    res.push(el)
    if (el.children && el.children.length > 0) {
      res = [...res, ...flatteningArray(el.children)]
    }
  })
  return res
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  // const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  const format = pattern || '{y}-{m}-{d}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
export function handleTree(data, id, parentId, children, rootId) {
  id = id || 'id'
  parentId = parentId || 'parentId'
  children = children || 'children'
  rootId = rootId || 0
  //对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  //循环所有项
  const treeData =  cloneData.filter(father => {
    let branchArr = cloneData.filter(child => {
    //返回每一项的子级数组
    return father[id] === child[parentId]
    });
    branchArr.length > 0 ? father.children = branchArr : '';
    //返回第一层
    return father[parentId] === rootId;
  });
  return treeData != '' ? treeData : data;
}

// 表单重置
export function resetForm(refName) {
  if (this.$refs[refName]) {
    this.$refs[refName].resetFields();
  }
}

/**
 * 判断两日期相隔天数
 * @param {*} startDate 
 * @param {*} endDate 
 */
export function getDaysBetween (startDate, endDate) {
  const startTimestamp = Date.parse(startDate)
  const endTimestamp = Date.parse(endDate)
  const days = (endTimestamp - startTimestamp) / (1*24*60*60*1000)
  return days
}